<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">新增菜单</el-button>
    </div>
    <div class="custom-tree-container">
      <div class="block">
        <el-tree :data="data4" :expand-on-click-node="false" :render-content="renderContent" node-key="id" default-expand-all />
      </div>
    </div>

    <el-dialog :visible.sync="dialogFormVisible" title="新增菜单" width="40%">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="100px" style="width: 400px;">
        <el-form-item label="上级菜单" prop="title">
          <el-select v-model="temp.module_id">
            <el-option key="0" :value="0" label="一级菜单">一级菜单</el-option>
            <el-option v-for="item in formatData" :key="item.id" :label="item.moduleName" :value="item.id">{{ optionItem(item) }}</el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="路径地址" prop="title">
          <el-input v-model="temp.moduleUrl" />
        </el-form-item>
        <el-form-item label="组件名称" prop="title">
          <el-input v-model="temp.moduleActionName" />
        </el-form-item>
        <el-form-item label="菜单名称" prop="title">
          <el-input v-model="temp.moduleName" />
        </el-form-item>
        <el-form-item label="描述" prop="title">
          <el-input v-model="temp.moduleDesc" />
        </el-form-item>
        <el-form-item label="菜单隐藏">
          <el-radio-group v-model="temp.moduleHide">
            <el-radio :label="0" :value="0" border>否</el-radio>
            <el-radio :label="1" :value="1" border>是</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
	fetchMenuAjax,
	addMenuAjax,
	updateMenuAjax,
	delMenuAjax
} from "@/api/authority";
import treeToArray from "@/components/TreeTable/eval";

let id = 1000;
export default {
	name: "MenuList",
	data() {
		return {
			data4: [],
			temp: {
				module_id: 0,
				moduleName: "",
				moduleActionName: "",
				moduleUrl: "",
				moduleDesc: "",
				moduleHide: ""
			},
			dialogFormVisible: false,
			rules: {}
		};
	},
	computed: {
		// 格式化下拉菜单数据源
		formatData: function() {
			let tmp;
			if (!Array.isArray(this.data4)) {
				tmp = [JSON.parse(JSON.stringify(this.data4))];
			} else {
				tmp = JSON.parse(JSON.stringify(this.data4));
			}
			const args = [tmp, true];
			return treeToArray.apply(null, args);
		}
	},
	created() {
		this.getList();
	},
	methods: {
		getList() {
			this.listLoading = true;
			fetchMenuAjax().then(response => {
				this.data4 = JSON.parse(JSON.stringify(response.data.data));
				this.listLoading = false;
			});
		},
		resetTemp() {
			this.temp = {
				module_id: 0,
				moduleName: "",
				moduleActionName: "",
				moduleUrl: "",
				moduleDesc: "",
				moduleHide: ""
			};
		},
		optionItem(item) {
			let element = "";
			if (item._level === 1) {
				return " " + item.moduleName;
			}
			for (let index = 0; index < item._level - 1; index++) {
				element += " │";
			}
			return element + " ├" + item.moduleName;
		},
		handleCreate(data) {
			console.log(data);
			this.resetTemp();
			this.dialogStatus = "create";
			this.dialogFormVisible = true;
		},
		createData() {
			this.$refs["dataForm"].validate(valid => {
				if (valid) {
					addMenuAjax(this.temp).then(() => {
						// this.list.unshift(this.temp);
						this.dialogFormVisible = false;
						this.$notify({
							title: "成功",
							message: "创建成功",
							type: "success",
							duration: 2000
						});
						this.getList();
					});
				}
			});
		},
		handleUpdate(node, data) {
			data.module_id = data.module_id
			this.temp = Object.assign({}, data); // copy obj
			this.dialogStatus = "update";
			this.dialogFormVisible = true;
			this.$nextTick(() => {
				this.$refs["dataForm"].clearValidate();
			});
		},
		updateData() {
			this.$refs["dataForm"].validate(valid => {
				if (valid) {
					const tempData = Object.assign({}, this.temp);
					console.log(tempData, 'kkk')
					updateMenuAjax(tempData).then(() => {
						this.dialogFormVisible = false;
						this.$notify({
							title: "成功",
							message: "更新成功",
							type: "success",
							duration: 2000
						});
						this.getList();
					});
				}
			});
		},
		append(data) {
			const newChild = { id: id++, label: "testtest", children: [] };
			if (!data.children) {
				this.$set(data, "children", []);
			}
			data.children.push(newChild);
		},
		remove(node, data) {
			// const parent = node.parent;
			// const children = parent.childNodes || parent;
			// const index = children.findIndex(d => d.id === data.id);
			// children.splice(index, 1);
		},
		renderContent(h, { node, data, store }) {
			return (
				<span class='custom-tree-node'>
					<span>{data.moduleName}</span>
					<span>
						<el-button
							type='primary'
							size='mini'
							on-click={() => this.handleCreate(data)}
						>
							添加子菜单
						</el-button>
						<el-button
							type='warning'
							size='mini'
							on-click={() => this.handleUpdate(node, data)}
						>
							编辑
						</el-button>
						<el-button
							type='success'
							size='mini'
							on-click={() => this.handleDelete(node, data)}
						>
							删除
						</el-button>
					</span>
				</span>
			);
		},
		handleDelete(node, row) {
			this.$confirm("确认删除该条数据吗?", "提示", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				type: "warning"
			}).then(() => {
				delMenuAjax(row).then((res) => {
					// const index = this.list.indexOf(row);
					// this.list.splice(index, 1);
					if (res.data.code !== 0) {
						this.$message({
							message: '删除失败',
							type: 'error',
							duration: 5 * 1000
						})
						return;
					}
					this.$notify({
						title: "成功",
						message: "删除成功",
						type: "success",
						duration: 2000
					});
					this.getList();
				});
			});
		}
	}
};
</script>
<style lang="scss">
.custom-tree-node {
	flex: 1;
	display: flex;
	align-items: center;
	justify-content: space-between;
	font-size: 14px;
	padding-right: 8px;
}
.el-tree-node {
	border-top: 1px solid #eee;
}
.el-tree-node__content {
	height: 34px;
}
</style>
